package com.sn.springboot_netty.server.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sn.springboot_netty.dao.UserMapper;
import com.sn.springboot_netty.model.User;
import com.sn.springboot_netty.server.IUserServer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServerImpl implements IUserServer {

    @Resource
    private UserMapper userMapper;

    @Resource(name = "myRedisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public List<User> queryUserList() {
        String key = "users";
        ValueOperations<String,List<User>> operations = redisTemplate.opsForValue();
        if(redisTemplate.hasKey(key)){ //存在,直接返回
            System.out.println("走redis");
            return operations.get(key);
        }
        //不存在，查询，保存，返回
        System.out.println("走mysql");
        PageHelper.startPage(1,10); //第一页，每页10条数据
        List<User> users = userMapper.queryUserList();
        PageInfo<User> pageInfo = new PageInfo<User>(users);
        operations.set(key,users,30, TimeUnit.SECONDS);
        return users;
    }

    @Override
    //@Cacheable(value = "user",key = "'user_'+#p0",cacheManager = "redisCacheManager")
    public User queryUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }
}
